<!-- 订单统计页面 -->
<template>
  <div class="order-statistics-container">
    <div class="page-header">
      <h2>订单统计</h2>
      <div class="header-actions">
        <el-date-picker
            v-model="selectedYear"
            :clearable="false"
            format="YYYY"
            placeholder="选择年份"
            type="year"
            value-format="YYYY"
            @change="handleYearChange"
        />
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 加载指示器 -->
    <div v-if="loading" class="loading-container">
      <el-icon :size="32" class="loading-icon">
        <Loading/>
      </el-icon>
      <p>加载统计数据中...</p>
    </div>

    <!-- 统计卡片区域 -->
    <el-row v-loading="loading" :gutter="20" class="stat-cards">
      <el-col :md="8" :sm="12" :xs="24">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单总数</span>
            </div>
          </template>
          <div class="stat-value">{{ overallStats.totalCount || 0 }}</div>
          <div class="stat-subtext">本月新增：{{ overallStats.currentMonthCount || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :md="8" :sm="12" :xs="24">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单总金额</span>
            </div>
          </template>
          <div class="stat-value">¥{{ formatAmount(overallStats.totalAmount) }}</div>
          <div class="stat-subtext">本月金额：¥{{ formatAmount(overallStats.currentMonthAmount) }}</div>
        </el-card>
      </el-col>
      <el-col :md="8" :sm="12" :xs="24">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均订单金额</span>
            </div>
          </template>
          <div class="stat-value">¥{{ formatAmount(overallStats.averageAmount) }}</div>
          <div class="stat-subtext">&nbsp;</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单状态分布 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :md="12" :xs="24">
        <el-card v-loading="loading" class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div id="statusChart" ref="statusChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :md="12" :xs="24">
        <el-card v-loading="loading" class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>月度订单金额趋势</span>
            </div>
          </template>
          <div id="trendChart" ref="trendChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 供应商TOP5 -->
    <el-card v-loading="loading" class="chart-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>供应商TOP5（按金额）</span>
        </div>
      </template>
      <el-table :data="supplierTop5" stripe style="width: 100%">
        <el-table-column align="center" type="index" width="50"/>
        <el-table-column label="供应商" min-width="180" prop="supplierName"/>
        <el-table-column align="center" label="订单数量" width="120">
          <template #default="scope">
            {{ scope.row.count }}
          </template>
        </el-table-column>
        <el-table-column align="right" label="总金额" min-width="150">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="占比" width="100">
          <template #default="scope">
            {{ calculatePercentage(scope.row.totalAmount, supplierTotalAmount) }}%
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script lang="ts">
import {computed, defineComponent, nextTick, onMounted, ref} from 'vue';
import * as echarts from 'echarts';
import {ElMessage} from 'element-plus';
import {Loading} from '@element-plus/icons-vue';
import {getOrderMonthlyTrend, getOrderStatistics} from '@/api/statistics';

export default defineComponent({
  name: 'OrderStatistics',
  components: {
    Loading
  },
  setup() {
    // 图表实例
    let statusChartInstance: echarts.ECharts | null = null;
    let trendChartInstance: echarts.ECharts | null = null;

    // 加载状态
    const loading = ref(true);

    // 整体统计数据
    const overallStats = ref<any>({});

    // 供应商数据
    // const supplierStats = ref<any>({});
    const supplierTop5 = ref<any[]>([]);
    const supplierTotalAmount = computed(() => {
      if (!supplierTop5.value.length) return 0;
      return supplierTop5.value.reduce((sum, item) => sum + parseFloat(item.totalAmount || 0), 0);
    });

    // 年份选择
    const selectedYear = ref<number>(new Date().getFullYear());

    // 趋势数据
    const trendData = ref<any[]>([]);

    // 格式化金额
    const formatAmount = (amount: any): string => {
      if (amount === undefined || amount === null) return '0.00';
      return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    };

    // 格式化日期
    // const formatDate = (date: string | Date): string => {
    //   if (!date) return '';
    //   if (typeof date === 'string') return date;
    //
    //   const d = new Date(date);
    //   const year = d.getFullYear();
    //   const month = String(d.getMonth() + 1).padStart(2, '0');
    //   const day = String(d.getDate()).padStart(2, '0');
    //   return `${year}-${month}-${day}`;
    // };

    // 计算百分比
    const calculatePercentage = (value: number, total: number): string => {
      if (!total) return '0.00';
      return ((value / total) * 100).toFixed(2);
    };

    // 初始化状态饼图
    const initStatusChart = () => {
      if (!overallStats.value.statusStats || !overallStats.value.statusStats.length) return;

      const chartDom = document.getElementById('statusChart');
      if (!chartDom) return;

      statusChartInstance = echarts.init(chartDom);

      const chartData = overallStats.value.statusStats.map((item: any) => ({
        name: item.status || '未知',
        value: parseInt(item.count)
      }));

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: chartData.map((item: any) => item.name)
        },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontWeight: 'bold'
              }
            },
            data: chartData
          }
        ]
      };

      statusChartInstance.setOption(option);
    };

    // 初始化趋势图
    const initTrendChart = () => {
      // 确保趋势数据非空，如果为空则初始化为空数组
      if (!trendData.value) {
        trendData.value = [];
      }

      const chartDom = document.getElementById('trendChart');
      if (!chartDom) {
        console.warn('找不到趋势图DOM元素');
        return;
      }

      // 如果图表实例已存在，先销毁
      if (trendChartInstance) {
        trendChartInstance.dispose();
      }

      trendChartInstance = echarts.init(chartDom);

      // 后端SQL已经保证返回12个月数据，直接使用
      // 只提取月份显示
      const xAxisData = trendData.value.map(item => {
        const monthStr = item.month || '';
        // 从YYYY-MM格式中提取月份
        const parts = monthStr.split('-');
        return parts.length > 1 ? `${parseInt(parts[1])}月` : monthStr;
      });

      const amountData = trendData.value.map(item => Number(item.totalAmount || 0));
      const countData = trendData.value.map(item => Number(item.count || 0));

      const option = {
        title: {
          show: false // 不显示标题，使用el-card的header
        },
        color: ['#5470c6', '#91cc75'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: function (params) {
            let result = params[0].name + '<br/>';
            params.forEach(item => {
              if (item.seriesName === '金额') {
                result += item.marker + ' ' + item.seriesName + ': ¥' + Number(item.value).toFixed(2) + '<br/>';
              } else {
                result += item.marker + ' ' + item.seriesName + ': ' + item.value + '个<br/>';
              }
            });
            return result;
          }
        },
        legend: {
          data: ['金额', '数量'],
          left: 'center',
          top: '10px'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '50px',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLine: {
            lineStyle: {
              color: '#E0E6F1'
            }
          },
          axisLabel: {
            color: '#666',
            formatter: '{value}'
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '金额',
            position: 'left',
            axisLabel: {
              formatter: '{value}元'
            },
            splitLine: {
              lineStyle: {
                type: 'dashed',
                color: '#E0E6F1'
              }
            }
          },
          {
            type: 'value',
            name: '数量',
            position: 'right',
            axisLabel: {
              formatter: '{value}个'
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '金额',
            type: 'bar',
            barWidth: '40%',
            data: amountData,
            itemStyle: {
              color: '#5470c6'
            }
          },
          {
            name: '数量',
            type: 'line',
            yAxisIndex: 1,
            data: countData,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              color: '#91cc75',
              width: 3
            },
            itemStyle: {
              color: '#91cc75',
              borderWidth: 2,
              borderColor: '#fff'
            }
          }
        ]
      };

      trendChartInstance.setOption(option);
    };

    // 初始化所有图表
    const initCharts = async () => {
      await nextTick();
      initStatusChart();
      initTrendChart();

      // 监听窗口变化，重绘图表
      window.addEventListener('resize', () => {
        statusChartInstance?.resize();
        trendChartInstance?.resize();
      });
    };

    // 获取订单统计数据
    const fetchOrderStats = async () => {
      try {
        loading.value = true;

        // 调用统计API
        const response = await getOrderStatistics();

        if (response && response.code === 200 && response.data) {
          // 处理API返回的数据
          overallStats.value = {
            totalCount: response.data.totalCount || 0,
            currentMonthCount: response.data.currentMonthCount || 0,
            totalAmount: response.data.totalAmount || 0,
            currentMonthAmount: response.data.currentMonthAmount || 0,
            averageAmount: response.data.averageAmount || 0,
            statusStats: response.data.statusStats || []
          };

          supplierTop5.value = response.data.supplierStats ?
              response.data.supplierStats.slice(0, 5).map((item: any) => ({
                supplierName: item.supplierName,
                count: item.count,
                totalAmount: item.totalAmount
              })) : [];

          // 初始化图表
          initCharts();
        } else {
          ElMessage.error('获取统计数据失败');
          console.error('获取统计数据失败：', response);
        }
      } catch (error) {
        console.error('获取订单统计数据失败', error);
        ElMessage.error('获取统计数据失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    };

    // 获取订单趋势数据
    const fetchOrderTrend = async () => {
      try {
        loading.value = true;

        const response = await getOrderMonthlyTrend(selectedYear.value);

        if (response && response.code === 200) {
          // 处理API返回的数据
          // 确保response.data是一个数组
          if (response.data && Array.isArray(response.data)) {
            // 确保数据按月份排序
            trendData.value = response.data.sort((a, b) => {
              const monthA = a.month || '';
              const monthB = b.month || '';
              return monthA.localeCompare(monthB);
            });
          } else {
            console.warn('API返回的趋势数据不是数组:', response.data);
            trendData.value = [];
          }

          // 重新初始化趋势图
          initTrendChart();
        } else {
          console.error('获取趋势数据失败：', response);
          trendData.value = [];
          // 即使没有数据也初始化图表，显示空图表
          initTrendChart();
        }
      } catch (error) {
        console.error('获取订单趋势数据失败', error);
        trendData.value = [];
        // 即使出错也初始化图表，显示空图表
        initTrendChart();
        ElMessage.error('获取趋势数据失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    };

    // 处理年份变化
    const handleYearChange = () => {
      // 获取新的趋势数据
      fetchOrderTrend();
    };

    // 刷新所有数据
    const refreshData = async () => {
      loading.value = true;
      try {
        await Promise.all([
          fetchOrderStats(),
          fetchOrderTrend()
        ]);
      } catch (error) {
        console.error('刷新数据失败', error);
      } finally {
        loading.value = false;
      }
    };

    // 组件挂载时初始化
    onMounted(() => {
      // 强制设置当前年份以避免1970年问题
      selectedYear.value = new Date().getFullYear();
      refreshData();
    });

    return {
      loading,
      selectedYear,
      overallStats,
      supplierTop5,
      supplierTotalAmount,
      formatAmount,
      calculatePercentage,
      handleYearChange,
      refreshData
    };
  }
});
</script>

<style scoped>
.order-statistics-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 50px 0;
}

.loading-icon {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 8px 0;
}

.stat-subtext {
  font-size: 14px;
  color: #909399;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  height: 100%;
}

.chart-container {
  height: 350px;
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-actions {
  display: flex;
  gap: 10px;
}
</style> 